package com.example.demo.juc.kuaishou;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liweizhi
 * @date 2020/7/8
 */
public class IncreaseNumber {
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    private int i = 0;

    void increase() {
        lock.lock();
        try {
            while (i > 0) {
                condition.await();
            }
            i++;
            System.out.println(Thread.currentThread().getName() + "    " + i);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void decrease() {
        lock.lock();
        try {
            while (i <= 0) {
                condition.await();
            }
            i--;
            System.out.println(Thread.currentThread().getName() + "    " + i);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        IncreaseNumber obj = new IncreaseNumber();
        Thread aThread = new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                obj.increase();
            }
        }, "A");

        Thread bThread = new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                obj.decrease();
            }
        }, "B");

        Thread cThread = new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                obj.increase();
            }
        }, "C");

        Thread dThread = new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                obj.decrease();
            }
        }, "D");

        aThread.start();
        bThread.start();
        cThread.start();
        dThread.start();
    }
}
